package v1

import (
	"fmt"
	"ksirGo/controller/tools/pagination"
	"ksirGo/controller/tools/response"
	"ksirGo/global"
	"ksirGo/middleware"
	"ksirGo/model"
	"ksirGo/utils"

	"github.com/gin-gonic/gin"
)

// 用户注册

type registerParamsType struct {
	Phone    string `form:"phone" json:"phone" binding:"required"`
	Password string `form:"password" json:"password" binding:"required"`
	Code     string `form:"code" json:"code" binding:"required"`
}

func Register(c *gin.Context) {
	var params registerParamsType

	if err := c.ShouldBindJSON(&params); err != nil {
		response.FailWithMessage(c, "请检查信息是否填写完整！"+err.Error())
	} else {
		var exist_user model.User
		rows := global.DB.Where("phone = ?", params.Phone).Find(&exist_user)
		if rows.RowsAffected > 0 {
			response.FailWithMessage(c, "当前用户已存在！")
		} else if len(params.Password) < 6 {
			response.FailWithMessage(c, "密码长度不少于6！")
		} else {
			// 验证码校验
			if utils.VerifyMessageCode(fmt.Sprintf("register-%s", params.Phone), params.Code) {
				var user = model.User{
					Phone:    params.Phone,
					Password: utils.GeneratePassword(params.Password),
				}
				global.DB.Create(&user)
				if global.DB.Error != nil {
					response.FailWithMessage(c, global.DB.Error.Error())
				} else {
					response.SuccessWithMessage(c, "注册成功！")
				}
			} else {
				response.FailWithMessage(c, "验证码错误！")
			}
		}
	}
}

// 账号密码登录接口

type loginParamsType struct {
	Phone        string `form:"phone" json:"phone" binding:"required"`
	Password     string `form:"password" json:"password" binding:"required"`
	CaptchaID    string `form:"captcha_id" json:"captcha_id" binding:"required"`
	CaptchaValue string `form:"captcha_value" json:"captcha_value" binding:"required"`
}

func FindUser(phone string) model.User {
	var user model.User
	global.DB.Where("phone = ?", phone).First(&user)
	return user
}

func LoginByPassword(c *gin.Context) {
	var params loginParamsType

	if err := c.ShouldBindJSON(&params); err != nil {
		// response.FailWithMessage(c, err.Error())
		response.FailWithMessage(c, "请检查信息是否填写完整！")
	} else {
		// 校验验证码
		if !utils.VerifyCaptcha(utils.ConfigType{
			Id:          params.CaptchaID,
			VerifyValue: params.CaptchaValue,
		}) {
			response.FailWithMessage(c, "请检查验证码是否正确！")
		} else {
			user := FindUser(params.Phone)
			if user.Password != utils.GeneratePassword(params.Password) {
				response.FailWithMessage(c, "请检查账号和密码是否填写正确！")
			} else {
				if token, tokenErr := middleware.GenerateToken(uint64(user.ID)); err != nil {
					response.FailWithMessage(c, tokenErr.Error())
				} else {
					response.SuccessWithDetailed(c, gin.H{
						"data":  user,
						"token": token,
					}, "登录成功！")
				}
			}
		}
	}
}

// 用户列表接口
type userListParamsType struct {
	Page int `form:"page" json:"page"` // 不传默认为1
	Size int `form:"size" json:"size"` // 不传默认为10
}

func UserList(c *gin.Context) {
	var params userListParamsType

	if paramsErr := c.ShouldBindQuery(&params); paramsErr != nil {
		response.FailWithMessage(c, paramsErr.Error())
		return
	}

	var list []model.User
	var total int64
	query := global.DB.Order("created_at desc").Scopes(pagination.Pagination(&params.Page, &params.Size)).Find(&list)
	if query.Error != nil {
		response.FailWithMessage(c, query.Error.Error())
	} else {
		total = pagination.Total(query)
		response.SuccessWithData(c, gin.H{
			"list":  list,
			"total": total,
			"page":  params.Page,
			"size":  params.Size,
		})
	}
}

func UserInfo(c *gin.Context) {
	if userId, exists := c.Get("userId"); exists {
		var user model.User
		query := global.DB.Where("id = ?", userId).Find(&user)
		if query.Error != nil {
			response.FailWithMessage(c, query.Error.Error())
		} else {
			response.SuccessWithData(c, gin.H{
				"data": user,
			})
		}
	}
}

// 头像上传
func AvatarUpload(c *gin.Context) {
	if userId, exists := c.Get("userId"); exists {
		var user model.User
		query := global.DB.Where("id = ?", userId).Find(&user)
		if query.Error != nil {
			response.FailWithMessage(c, "用户不存在！")
		} else {
			file, _ := c.FormFile("file")
			if imageUrl, _, err := utils.UploadFileAvatar(file); err != nil {
				response.FailWithMessage(c, err.Error())
			} else {
				user.Avatar = *imageUrl
				db := global.DB.Save(&user)
				if db.Error != nil {
					response.FailWithMessage(c, db.Error.Error())
				} else {
					response.SuccessWithData(c, gin.H{
						"data": user,
					})
				}
			}
		}
	}
}
